﻿using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Xml.Serialization;
using System.Xml;

namespace Adams.Shared
{
    public static class Serialize
    {
        public static string SerializeJson(object obj)
        {
            string retVal = string.Empty;
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, obj);
                retVal = Encoding.Default.GetString(ms.ToArray());
                ms.Close();
            }
            return retVal;

        }

        public static T DeserializeJson<T>(string json)
        {
            T obj = default(T);
            using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                obj = (T)serializer.ReadObject(ms);
                ms.Close();
            }
            return obj;
        }

        public static string SerializeXml(object obj)
        {
            string retVal = string.Empty;
            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.Serialize(ms, obj);
                retVal = Encoding.Default.GetString(ms.ToArray());
                ms.Close();
            }
            return retVal;
        }

        public static T DeserializeXml<T>(string xml)
        {
            T obj = default(T);
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (StringReader stringReader = new StringReader(xml))
            {
                using (XmlTextReader xmlReader = new XmlTextReader(stringReader))
                {
                    obj = (T)serializer.Deserialize(xmlReader);
                    xmlReader.Close();
                }
                stringReader.Close();
            }
            return obj;
        }
    }
}
